import React from 'react';
import { history, RequestConfig } from 'umi';
import { currentUser as queryCurrentUser } from './services/login';
import settings from '../config/settings';
import dayjs from 'dayjs';
// import { PageLoading } from '@ant-design/pro-layout';

const { loginPath, authTokenName } = settings;

/** 获取用户信息比较慢的时候会展示一个 loading */
// export const initialStateConfig = {
//   loading: <div />,
// };

/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */
export async function getInitialState(): Promise<{
  currentUser?: API.CurrentUser | null;
  // fetchUserInfo?: () => Promise<API.CurrentUser | undefined>;
  // setToken?: (token: string) => void;
  logout?: () => void;
}> {
  // const fetchUserInfo = async () => {
  //   try {
  //     const msg = await queryCurrentUser();
  //     return msg.data;
  //   } catch (error) {
  //     // history.push(loginPath);
  //   }
  //   return undefined;
  // };
  // const setToken = (token: string) => {
  //   localStorage.setItem(authTokenName, token);
  // };
  // 如果是登录页面，不执行
  // if (history.location.pathname !== loginPath) {
  // const currentUser = await fetchUserInfo();
  // return {
  //   fetchUserInfo,
  //   setToken,
  //   removeToken,
  //   currentUser,
  // };
  // }

  const currentUser = getCurrentUser();

  return {
    // fetchUserInfo,
    currentUser,
    // setToken,
    logout,
  };
}

export function render(oldRender: Function) {
  // const { location } = history;
  // 如果没有登录，重定向到 login
  if (!getTokenStorage() && location.pathname !== loginPath) {
    logout();
    oldRender();
  } else {
    oldRender();
  }
}

// Request
export const request: RequestConfig = {
  errorConfig: {
    adaptor: (resData) => {
      console.log(resData);
      return {
        ...resData,
        success: resData.code == 200,
        errorMessage: resData.msg || resData.message || resData.error,
      };
    },
  },
  requestInterceptors: [
    (url, options) => {
      const token = getTokenStorage();
      // if (token) {
      //   options.headers = {
      //     ...options?.headers,
      //     authorization: `Bearer ${token}`,
      //   };
      // }
      if (options.method == 'post') {
        options.data = {
          clientTime: dayjs().format('YYYY_MM_DD_HH_mm_ss'),
          clientVersion: '1',
          operatorId: getAdminId(),
          request: options.data,
          // requestId: '',
          systemId: '4',
          tenantId: 1,
          token,
        };
      }
      return {
        url,
        options,
      };
    },
  ],
  responseInterceptors: [
    (response) => {
      if (response.status == 401) {
        logout();
      }
      return response;
    },
  ],
};

// get currentUser
const getCurrentUser = (): API.CurrentUser | null => {
  const adminStr = localStorage.getItem('adminInfo');
  if (adminStr) {
    return JSON.parse(adminStr);
  } else {
    return null;
  }
};

// get token
const getTokenStorage = (): string | undefined => {
  const currentUser = getCurrentUser();
  return currentUser?.token;
};

// get adminId
const getAdminId = (): number | undefined => {
  const currentUser = getCurrentUser();
  return currentUser?.adminId;
};

// logout
const logout = () => {
  location.href = loginPath;
  // localStorage.removeItem(authTokenName);
};
